package com.xma.providerpay.controller;

import com.xma.providerpay.service.PaymentService;
import com.xma.springcloud.common.ResponseResult;
import com.xma.springcloud.entity.Payment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * (Payment)表控制层
 *
 * @author makejava
 * @since 2020-06-22 13:48:32
 */
@RestController
@RequestMapping("/payment")
public class PaymentController {
    private static final Logger logger = (Logger) LoggerFactory.getLogger(PaymentController.class);

    /**
     * 服务对象
     */
    @Resource
    private PaymentService paymentService;
    @Value("${server.port}")
    private String serverPort;
    //服务发现
    @Resource
    private DiscoveryClient discoveryClient;

    @PostMapping(value = "/create")
    public ResponseResult create(@RequestBody Payment payment){
        int result = paymentService.insert(payment);
        logger.info("插入数据结果 :"+result);
        if(result > 0){
            return new ResponseResult(200,"插入数据库成功,服务端口号:" +  serverPort,result);
        }else {
            return new ResponseResult(500,"插入数据库失败",null);
        }
    }
    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping(value = "/get/{id}")
    public ResponseResult selectOne(@PathVariable("id") Long id) {
        Payment payment = this.paymentService.queryById(id);
        if(payment!= null){
            return new ResponseResult(200,"查询数据成功,服务端口号:" +  serverPort,payment);
        }else{
            return new ResponseResult(200,"插入数据库失败");
        }
    }

    @GetMapping(value = "/discovery")
    public Object discovery(){
        List<String> services = discoveryClient.getServices();
        for (String element : services) {
            logger.info("*****element:" + element);
        }
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for (ServiceInstance instance : instances) {
            logger.info(instance.getServiceId() + "\t" + instance.getHost() + "\t"
            +  instance.getPort() + "\t" + instance.getUri());
        }
        return  this.discoveryClient;
    }

    @GetMapping(value = "/lb")
    public String getPaymentLB(){
        return serverPort;
    }

    @GetMapping(value = "/feign/timeout")
    public String paymentFeignTimeOut(){
        try {
            TimeUnit.SECONDS.sleep(3);
        }catch (Exception e){
            e.printStackTrace();
        }
        return serverPort;
    }

    @GetMapping("/zipkin")
    public String paymentZipkin(){
        return "hi,i'am paymentzipkin server fall back ,welcome to xma 哈哈哈.....";
    }
}